/**
 * 发送get异步请求
 * @param {stirng} url
 * @param {object} params
 * @param {object} headers
 */
function get(url, params, headers = {}) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    let temp = [];
    for (let key in params) {
      temp.push(`${key}=${params[key]}`);
    }
    xhr.open("get", `${url}?${temp.join(`&`)}`);
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          let res = JSON.parse(xhr.responseText);
          resolve(res);
        } else {
          reject(xhr.status);
        }
      }
    };
    for (let key in headers) {
      xhr.setRequestHeader(key, headers[key]);
    }
    xhr.send();
  });
}

/**
 * 发送post异步请求
 * @param {stirng} url
 * @param {object} params
 * @param {object} headers
 */
function post(url, params, headers = {}) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("post", url);
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          let res = JSON.parse(xhr.responseText);
          resolve(res);
        } else {
          reject(xhr.status);
        }
      }
    };
    xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    for (let key in headers) {
      xhr.setRequestHeader(key, headers[key]);
    }
    let temp = [];
    for (let key in params) {
      temp.push(`${key}=${params[key]}`);
    }
    xhr.send(temp.join(`&`));
  });
}
